package cc.kzc.adminauth.auth;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import cc.kzc.adminauth.auth.bo.LoginUser;
import cc.kzc.adminauth.redis1.cache.LoginUserCache;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	private LoginUserCache loginUserCache;

	JwtAuthenticationTokenFilter(LoginUserCache loginUserCache) {
		this.loginUserCache = loginUserCache;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		// 获取token
		String token = request.getHeader("tk");
		String userid = null;
		if (StringUtils.hasText(token)) {
			try {
				Claims claims = JwtProcessor.parseJWT(token);
				userid = claims.getSubject();
			} catch (Exception e) {
				log.warn("非法的token", e.getMessage());
			}
		}

		if (null != userid && SecurityContextHolder.getContext().getAuthentication() == null) {
			// 从redis中获取用户信息
			LoginUser loginUser = loginUserCache.get(userid);
			if (null != loginUser) {
				// 存入SecurityContextHolder
				UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
						loginUser, null, null);
				SecurityContextHolder.getContext().setAuthentication(authenticationToken);
			}
		}

		// 放行
		filterChain.doFilter(request, response);
	}
}
